package com.stylefeng.guns.modular.pay.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.excel.CreateExcel;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.FileUtil;
import com.stylefeng.guns.core.util.FileZip;
import com.stylefeng.guns.modular.pay.dto.TransACDTO;
import com.stylefeng.guns.modular.pay.dto.TransDTO;
import com.stylefeng.guns.modular.pay.dto.TransParams;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.model.TransHistory;
import com.stylefeng.guns.modular.pay.service.ITransHistoryService;

/**
 * 交易流水控制器
 *
 * @author fengshuonan
 * @Date 2018-08-17 16:25:57
 */
@Controller
@RequestMapping("/transHistory")
public class TransHistoryController extends BaseController {

    private String PREFIX = "/pay/transHistory/";

    @Autowired
    private ITransHistoryService transHistoryService;

    /**
     * 跳转到交易流水首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "transHistory.html";
    }

    /**
     * 跳转到添加交易流水
     */
    @RequestMapping("/transHistory_add")
    public String transHistoryAdd() {
        return PREFIX + "transHistory_add.html";
    }

    /**
     * 跳转到修改交易流水
     */
    @RequestMapping("/transHistory_update/{transHistoryId}")
    public String transHistoryUpdate(@PathVariable Integer transHistoryId, Model model) {
        TransHistory transHistory = transHistoryService.selectById(transHistoryId);
        model.addAttribute("item",transHistory);
        LogObjectHolder.me().set(transHistory);
        return PREFIX + "transHistory_edit.html";
    }
    
    @RequestMapping("/transHistory_detail/{transId}")
    public String detail(@PathVariable Integer transId, Model model) {
    	TransHistory transHistory = transHistoryService.selectById(transId);
        model.addAttribute("item",transHistory);
        LogObjectHolder.me().set(transHistory);
        return PREFIX + "transHistory_detail.html";
    }

    /**
     * 获取交易流水列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(TransHistory history) {
    	 Page<TransHistory> page = new PageFactory<TransHistory>().defaultPage();
         List<TransHistory> result = transHistoryService.list(page,history);
         page.setRecords(result);
         return super.packForBT(page);
    }

    /**
     * 新增交易流水
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TransHistory transHistory) {
        transHistoryService.insert(transHistory);
        return SUCCESS_TIP;
    }

    /**
     * 删除交易流水
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer transHistoryId) {
        transHistoryService.deleteById(transHistoryId);
        return SUCCESS_TIP;
    }

    /**
     * 修改交易流水
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(TransHistory transHistory) {
        transHistoryService.updateById(transHistory);
        return SUCCESS_TIP;
    }

    /**
     * 交易流水详情
     */
    @RequestMapping(value = "/detail/{transHistoryId}")
    @ResponseBody
    public Object detail(@PathVariable("transHistoryId") Integer transHistoryId) {
        return transHistoryService.selectById(transHistoryId);
    }
    
    /**
     * 订单导出
     */
    @RequestMapping(value = "/download")
    @ResponseBody
    public void download(TransParams param,HttpServletRequest request,HttpServletResponse response) {
		OutputStream fOut = null;
		try {
			TransACDTO re =transHistoryService.getExportData(param);
			setResponseHeader(response, re.getTitle());
			fOut = response.getOutputStream();
			toExcel(re, request, 20000, re.getTitle(), fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
    }
    
    public void toExcel(TransACDTO acdto, HttpServletRequest request, int limit, String fileName,OutputStream out) throws IOException {
		List<String> fileNames = new ArrayList<String>();// 用于存放生成的文件名称
		String excelZipPath = request.getServletContext().getRealPath("download/");
		File excelZip = new File(excelZipPath);// 压缩文件
		if (!excelZip.exists()) {
			excelZip.mkdirs();
		}
		File zip = new File(excelZip.getPath()+ File.separator + fileName + ".zip");
		List<TransDTO> list = acdto.getDetail();
		int num = list.size() / limit + 1;
		for (int j = 0; j < num; j++) {
			String splitFileName = excelZipPath + File.separator + fileName + "-" + j + ".xls";
			fileNames.add(splitFileName);
			int min = (list.size() - j * limit + 1) > (limit + 1) ? (limit + 1) : (list.size() - j * limit + 1);
			List<TransDTO> subList  = new ArrayList<TransDTO>();
			for (int i = 1; i < min; i++) {
				 subList.add(list.get(limit * (j) + i - 1));
			}
			HSSFWorkbook wb = (HSSFWorkbook) CreateExcel.getInstance().CreateNewExcelNoTemplate(fileName, subList).getWorkbook();
			FileOutputStream o = new FileOutputStream(splitFileName);
			try {
				wb.write(o);
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				o.flush();
				o.close();
			}
		}
		File srcfile[] = new File[fileNames.size()];
		for (int i = 0, n = fileNames.size(); i < n; i++) {
			srcfile[i] = new File(fileNames.get(i));
		}
		FileZip.ZipFiles(srcfile, zip);
		FileInputStream inStream = new FileInputStream(zip);
		byte[] buf = new byte[4096];
		int readLength;
		while (((readLength = inStream.read(buf)) != -1)) {
			out.write(buf, 0, readLength);
		}
		inStream.close();
		FileUtil.deleteDir(excelZip);
	}
}
